<?php
namespace Users\Controller;
use Hybrid_Auth;
use ScnSocialAuth\Mapper\Exception as MapperException;
use ScnSocialAuth\Mapper\UserProviderInterface;
use ScnSocialAuth\Options\ModuleOptions;
use Zend\View\Model\ModelInterface;
use Zend\View\Model\ViewModel;
use Zend\Mvc\Controller\AbstractActionController;
         // <-- Add this import
use Users\Form\UserForm; 
use Zend\View\Model\JsonModel;
use Zend\Session\Container;

class UsersController extends AbstractActionController
{
	
    public function indexAction()
	{
		
	}
	public function cronusernotificationsAction()
	{
		global $pendingmailsubject;				
		global $pendingmailMessage;
		$sentnotificationTable=$this->getServiceLocator()->get('Users\Model\SentNotificationsFactory');
		$sent_notification_gmails=$sentnotificationTable->getallusersemails();
		$ids=array();
		if($sent_notification_gmails->count()>0)
		{ 			
			foreach($sent_notification_gmails as $mailcontent)
			{				
				//Details for mailing
				$offer_name=$mailcontent->offer_name;
				$to=$mailcontent->email;
				$started_date=$mailcontent->starting_date;
				$end_date=$mailcontent->ending_date;
				$offer_amount=$mailcontent->offer_amount;
				$dis_percentage=$mailcontent->percent_discount;
				$user_name=$mailcontent->user_name;				
				$pendingmailsubject = $mailcontent->offer_name;
				$body=$pendingmailMessage;
				$body = str_replace("<FULLNAME>",$user_name, $body);
				$body = str_replace("<DISCOUNTPERCENTAGE>",$dis_percentage, $body);
				$body = str_replace("<OFFERNAME>",$offer_name, $body);
				$body = str_replace("<AMOUNTOFFER>",$offer_amount, $body);
				$body = str_replace("<STARTEDDATE>",$started_date, $body);
				$body = str_replace("<ENDDATE>",$end_date, $body);
				if(sendMail($to,$pendingmailsubject,$body))
				{
					$ids[]=$mailcontent->sent_offer_notification_id;
				}
			}	
		}
		if(count($ids))
		{
			 $pendingmails=$sentnotificationTable->updatemailstatus($ids);
		}
		echo "Pending mails are sended";exit;			
	}
	public function addTestimonyAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$testimonyTable=$this->getServiceLocator()->get('Users\Model\TestimonialsFactory');
		if(isset($_POST['hid_testimony']) && $_POST['hid_testimony']!=""){
			$testimony_update_status = $testimonyTable->addTestimony($_POST);
			if($testimony_update_status>=0){
				 return $this->redirect()->toUrl($baseUrl.'users/testimonial');			
			}
		}else if(isset($_POST['testimony_text']) && $_POST['testimony_text']!=""){
			$testimony_add_status = $testimonyTable->addTestimony($_POST);
			if($testimony_add_status>0){				
				 return $this->redirect()->toUrl($baseUrl.'users/testimonial');			
			}
		}else  if(isset($_GET['testimony_id']) && $_GET['testimony_id']!=""){
			$testimony_details = $testimonyTable->editTestimony($_GET['testimony_id']);
			return new ViewModel(array(
				'textimony_details' 	=> $testimony_details,
			));
		}
	}
	public function deleteTestimonyAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$testimonyTable=$this->getServiceLocator()->get('Users\Model\TestimonialsFactory');
		if(isset($_GET['testimony_id']) && $_GET['testimony_id']!=""){
			$delete_status = $testimonyTable->deleteTestimony($_GET['testimony_id']);
			if($delete_status>0){
				 return $this->redirect()->toUrl($baseUrl.'users/testimonial');
			}
		}
	}
	public function checkregemailAction()
	{
		if (isset($_POST['email']) && $_POST['email']!=""){				   
				$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
				$email = $usersTable->checkUniqueRecord($_POST['email']);
				if($email!=0){
					$result = new JsonModel(array(					
						'output' 	=> 'success',
					));					
				}else{
					$result = new JsonModel(array(					
						'output' 	=> 'notsuccess',
					));	
				}
			return $result;			
		}
	}
	public function sendPasswordResetUrlAction(){	
		$baseUrls = $this->getServiceLocator()->get('config');
        $baseUrlArr = $baseUrls['urls'];
        $baseUrl = $baseUrlArr['baseUrl'];
		$sentMail=0;
		if(isset($_POST['email']) && $_POST['email']!=""){
			$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
			$forgetTable=$this->getServiceLocator()->get('Users\Model\ForgetpasswordFactory');
			$emailCount = $usersTable->checkEmail($_POST['email']);
			if($emailCount!=''){				
				$user_id=$emailCount->user_id;
				$username=ucfirst($emailCount->user_name);
				$token = getUniqueCode('10');
				$user_type_id=$emailCount->user_type_id;
				if($user_type_id=='1'){
					$type='admin/';
				}else{
					$type='';
				}
				$mailExit=$forgetTable->getmailfromfgtpwd($_POST['email']);
				if($mailExit!=""){
					$alreadyexitid=$mailExit->forget_id;
					$getuserId=$forgetTable->addForgetpwd($alreadyexitid,$_POST['email'],$emailCount->user_id,$token);
				}else{
					$alreadyexitid='';
					$getuserId=$forgetTable->addForgetpwd($alreadyexitid,$_POST['email'],$emailCount->user_id,$token);
				}
				global $forgotPasswordSubject;				
				global $frogotPasswordMessage;
				$frogotPasswordMessage = str_replace("<FULLNAME>","$username", $frogotPasswordMessage);
				$frogotPasswordMessage = str_replace("<PASSWORDLINK>",$baseUrl.$type."newpassword?token=".$token, $frogotPasswordMessage);	
				$to=$emailCount->email;	
				$sentMail=sendMail($to,$forgotPasswordSubject,$frogotPasswordMessage);
				if($sentMail>0){
					return $result = new JsonModel(array(					
						'output' => 'success',
					));	
				}else{
					return $result = new JsonModel(array(	
						'output' => 'server-error',
					));	
				}				
			}else{
				return $result = new JsonModel(array(					
					'output' 	=> 'notsuccess',
				));
			}
		}		
	}
	public function updatepasswordAction(){
		$token=$_GET['token'];
		$tokeninfo=array();
		$exitToke=0;
		$forgetTable=$this->getServiceLocator()->get('Users\Model\ForgetpasswordFactory');
		$tokenExit=$forgetTable->gettoken($token);		
		if(count($tokenExit)!=0){		
			foreach($tokenExit as $tokeninfo){}				
				if($tokeninfo->forget_id > 0){
					$exitToken=1;
				}else{
					$exitToken=0;
				}
		}else{
			$exitToken=0;
		}
		$viewModel = new ViewModel(
			array('existtoken'=>$exitToken)
		);	
		return $viewModel;		
	}
	public function setnepasswordAction(){
		if(isset($_POST['token']) && $_POST['token']!=""){
			$token=$_POST['token'];		
			$tokeninfo=array();
			$forgetTable=$this->getServiceLocator()->get('Users\Model\ForgetpasswordFactory');
			$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
			$tokenExit=$forgetTable->gettoken($token);
			foreach($tokenExit as $tokeninfo){}
			if($tokeninfo->user_id>0){
				$changepwd = $usersTable->changepwd($_POST['cnfpwrd'],$tokeninfo->user_id);						
				if($changepwd>=0){
					$deletetokenid=$forgetTable->deletetoken($tokeninfo->forget_id);
					$result = new JsonModel(array(					
						'output' => 'success',
						'success'=>false,
					));			
				}else{
					$result = new JsonModel(array(					
						'output' => 'not success',
						'not success'=>false,
					));
				}				
			}else{
				$result = new JsonModel(array(					
					'output' => 'not success',
					'not success'=>false,
				));	
			}
			return $result;	
		}
	}	
	public function logoutAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		unset($_SESSION['user']);
		unset($_SESSION['orders']);
		return $this->redirect()->toUrl($baseUrl);
	}
	public function registerAction()
	{
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];		
		if(isset($_POST['inputEmail']) && $_POST['inputEmail']!=""){
			$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
			$userdeailsTable=$this->getServiceLocator()->get('Users\Model\UserdetailsFactory');			
			if($_POST['mod_type']=='reg_user'){
				$regAuth='user';
			}else{
				$regAuth='admin';
			}
			$getuserId=$usersTable->addUser($_POST,$regAuth);
			if($getuserId!=0){
				$add_status=$userdeailsTable->addUserdetails($getuserId,$_POST);
				if($add_status!=0){
					if($_POST['mod_type']=='reg_user'){				
						global $regUserSubject;
						global $regUserMessage;
						$regUserMessage = str_replace("<FULLNAME>",$_POST['inputUserName'], $regUserMessage);
						$to=$_POST['inputEmail'];
						$sentMail=sendMail($to,$regUserSubject,$regUserMessage);
						if($sentMail>0){
							$userdetails = $usersTable->checkLogin($_POST);
							if($userdetails!=''){			
								$user_session = new Container('user');			
								$user_session->username=$userdetails->user_name;
								$user_session->email=$userdetails->email;
								$user_session->display_name=$userdetails->user_name;
								$user_session->user_id=$userdetails->user_id;
								$user_session->user_type=$userdetails->user_type;
								$user_session->user_type_id=$admindetails->user_type_id;
								return $this->redirect()->toUrl($baseUrl.'edit-user?user_id='.$user_session->user_id);
							}else{
								echo "Not success";exit;		
							}								
						}else{
							$userdetails = $usersTable->checkLogin($_POST);
							if($userdetails!=''){			
								$user_session = new Container('user');			
								$user_session->username=$userdetails->user_name;
								$user_session->email=$userdetails->email;
								$user_session->display_name=$userdetails->user_name;
								$user_session->user_id=$userdetails->user_id;
								$user_session->user_type=$userdetails->user_type;
								$user_session->user_type_id=$admindetails->user_type_id;
								return $this->redirect()->toUrl($baseUrl.'edit-user?user_id='.$user_session->user_id);
							}else{
								echo "Not success";exit;		
							}	
						}
					}else if($regAuth=='admin'){
						return $this->redirect()->toUrl($baseUrl.'admin/user-lists');
					}
				}
			}
		}else{
			$usertypeTable=$this->getServiceLocator()->get('Users\Model\UsersTypeFactory');
			$getAllusertypes=$usertypeTable->getAllusertypes();
			return new ViewModel(array(
				'allUsertypes' 	=> $getAllusertypes,
			));
		}
	}
	public function checkPasswordAction(){ 
		$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
		$pwdExit = $usersTable->getpassword($_POST['oldpasswrd'],$_POST['userId']);		
		if($pwdExit>0){			
			$result = new JsonModel(array(					
				'output' => 'success',
			));			
		}else{
			$result = new JsonModel(array(					
				'output' => 'not success',
			));
		}
		return $result;		
	}	
	public function changePasswordAction(){
		if(isset($_POST['cnfpwrd'])){
			$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');	
			$changepwd = $usersTable->changepwd($_POST['cnfpwrd'],$_POST['userId']);	
			if($changepwd>0){			
				$result = new JsonModel(array(					
					'output' => 'success',
				));			
			}else{
				$result = new JsonModel(array(					
					'output' => 'not success',
				));
			}
			return $result;	
		}		
		
	}
	public function forgetpasswordAction(){
		
	}
	public function testimonialAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$testimonyTable=$this->getServiceLocator()->get('Users\Model\TestimonialsFactory');
		$paginator=$testimonyTable->testimonialsList(true);
		$paginator->setCurrentPageNumber((int)$this->params()->fromQuery('page', 1));
		$paginator->setItemCountPerPage(10);
		return new ViewModel(array(
				'testimonyLists' 	=> $paginator,
			));
	}
	public function editUserAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');	
		$userdeailsTable=$this->getServiceLocator()->get('Users\Model\UserdetailsFactory');		
		if(isset($_POST['hid_user_id']) && $_POST['hid_user_id']!=""){
			$update_user_status = $usersTable->updateUser($_POST);
			if($update_user_status>=0){
				$update_userdetails_status = $userdeailsTable->updateUserDetails($_POST);
				if($update_userdetails_status>=0){
					return $this->redirect()->toUrl($baseUrl);
				}
			}
		}else if(isset($_GET['user_id']) && $_GET['user_id']){
			$userdetails = $usersTable->getuserDetailes($_GET['user_id']);
			$districtTable=$this->getServiceLocator()->get('Category\Model\DistrictsFactory');
			$districtsAll=$districtTable->allDistricts();
			$areaTable=$this->getServiceLocator()->get('Category\Model\AreaFactory');
			$areasAll=$areaTable->allAreas();
			$locationTable=$this->getServiceLocator()->get('Category\Model\LocationFactory');
			$locationsAll=$locationTable->allLocations();
			$result = new ViewModel(array(
				'userdetails'   =>$userdetails,
				'alldistricts' 	=> $districtsAll,
				'areasAll' 	    => $areasAll,
				'locationsAll' 	=> $locationsAll,
				
			));	
			return $result;	
		}
		
	}
	public function getSubCategoriesAction(){
		if(isset($_POST['cat_id']) && $_POST['cat_id']!=''){
			$subcategoryTable=$this->getServiceLocator()->get('Category\Model\SubCategoryFactory');
			$sub_categories = $subcategoryTable->subCategories($_POST['cat_id']);
			$html="";			
			if($sub_categories->count()>0){
				$html.='<option value="">Select sub category</option>';
				foreach($sub_categories as $subCategory){
					if($_POST['sesss_sub_cat']==$subCategory->sub_cat_id){
						$html.='<option value="'.$subCategory->sub_cat_id.'" selected="selected">'.$subCategory->sub_category_name.'</option>';
					}else{
						$html.='<option value="'.$subCategory->sub_cat_id.'">'.$subCategory->sub_category_name.'</option>';
					}
				}
			}else{
				$html.='<option value="">Select sub category</option>';		
			}
		}else{
			$html="";
			$html.='<option value="">Select sub category</option>';	
		}
		$result = new JsonModel(array(					
			'output' 		=> 'success',
			'sub_categories'	=>	$html,
		));	
		return $result;	
		
	}
	public function adPostingAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$langugeTable=$this->getServiceLocator()->get('Category\Model\LanguageFactory');
		$categoryTable=$this->getServiceLocator()->get('Category\Model\CategoryFactory');
		$districtTable=$this->getServiceLocator()->get('Category\Model\DistrictsFactory');	
		$areaTable=$this->getServiceLocator()->get('Category\Model\AreaFactory');
		$locationTable=$this->getServiceLocator()->get('Category\Model\LocationFactory');
		$radiusTable=$this->getServiceLocator()->get('Category\Model\RadiusFactory');
		$packagesperoidTable=$this->getServiceLocator()->get('Category\Model\PeriodOfPackagesFactory');
		$imagedimensionsTable=$this->getServiceLocator()->get('Category\Model\ImageDimensionsFactory');
		$adstypeTable=$this->getServiceLocator()->get('Category\Model\AddTypeFactory');
		$numwordsTable=$this->getServiceLocator()->get('Category\Model\NumberWordsFactory');
		if(isset($_POST['ses_current_order']) && $_POST['ses_current_order']!=''){
			$update_session_order=$_POST['ses_current_order'];
			$main_array=array();
			$paper_print=array();
			$magazine=array();
			$home_delivery=array();
			foreach($_POST as $key=>$value){
				if(strpos($key,'paper') !== false) {
					if( $_POST['paper_populationpaperdrop'] != ''&& $value!='' )
					{
						$paper_print[$key]=$value;
					}
				}else if(strpos($key,'magazine') !== false){
					if( $_POST['magazine_titleMagazine'] != '' && $value!='')
					{
						$magazine[$key]=$value;
					}
				}else if(strpos($key,'home') !== false){
				if( $_POST['home_titleHome'] != '' && $value!='' )
					{
						$home_delivery[$key]=$value;
					}
				}else{
					$main_array[$key]=$value;
				}
				$_SESSION['orders'][$update_session_order]['Main_array']=$main_array;				
				if(!empty($paper_print)){
					$_SESSION['orders'][$update_session_order]['Print_Paper']=$paper_print;
				}
				if(count($magazine)>0){
					$_SESSION['orders'][$update_session_order]['Magazine']=$magazine;
				}
				if(!empty($home_delivery)){
					$_SESSION['orders'][$update_session_order]['Home_delivery']=$home_delivery;
				} 	
				if( !isset($_POST['paper_print']) ) {
					unset($_SESSION['orders'][$update_session_order]['Print_Paper']);
				}
				if( !isset($_POST['magazine_magazineCheck']) ){
					unset($_SESSION['orders'][$update_session_order]['Magazine']);
				}
				if( !isset($_POST['home_homedelevarycheck']) ){
					unset($_SESSION['orders'][$update_session_order]['Home_delivery']);
				}
			}
			return $this->redirect()->toUrl($baseUrl.'users/confirm-order');		
		}else if(isset($_POST['language'])){
		    $main_array=array();
			$paper_print=array();
			$magazine=array();
			$home_delivery=array();
			foreach($_POST as $key=>$value){
				if(strpos($key,'paper') !== false) {
					if( $_POST['paper_populationpaperdrop'] != '' && $value!='')
					{
						$paper_print[$key]=$value;
					}
				}else if(strpos($key,'magazine') !== false){
					if( $_POST['magazine_titleMagazine'] != '' && $value!='')
					{
						$magazine[$key]=$value;
					}
				}else if(strpos($key,'home') !== false){
					if( $_POST['home_titleHome'] != '' && $value!='')
					{
						$home_delivery[$key]=$value;
					}
				}else{
					$main_array[$key]=$value;
				}
				
			}		   
			if(isset($_SESSION['orders'])){	
				$orderCount=count($_SESSION['orders']);					
			}else{	
				$orderCount=0;	
				$user_session = new Container('orders');
				$_SESSION['orders']=array();
			}				
				$_SESSION['orders'][$orderCount]['Main_array']=$main_array;				
				if(!empty($paper_print)){
					$_SESSION['orders'][$orderCount]['Print_Paper']=$paper_print;
				}
				if(count($magazine)>0){
					$_SESSION['orders'][$orderCount]['Magazine']=$magazine;
				}
				if(!empty($home_delivery)){
					$_SESSION['orders'][$orderCount]['Home_delivery']=$home_delivery;
				} 			
			return $this->redirect()->toUrl($baseUrl.'users/confirm-order');		
		}else if(isset($_GET['currentOrder']) && $_GET['currentOrder']!=''){
			$getLanguges=$langugeTable->allLanguges();
			$getCategories=$categoryTable->getallCategories();
			$districtLists = $districtTable->allDistricts();
			$get_all_radius = $radiusTable->getallRadius();
			$get_all_periods= $packagesperoidTable->allperiodofpackages();
			$get_all_dimensions= $imagedimensionsTable->getallDimensions()->buffer();
			$get_adMode= $adstypeTable->alladstypes()->buffer();
			$base_range = $numwordsTable->baseRange();
			$result = new ViewModel(array(
				'all_languages'           => $getLanguges,
				'all_categories'          => $getCategories,
				'list_districts'          => $districtLists,
				'list_radius'             => $get_all_radius,
				'list_periodfor_pakages'  => $get_all_periods,
				'list_image_dimensions'   => $get_all_dimensions,
				'list_admodes'            => $get_adMode,
				'base_range'              => $base_range,
				'session_data'            => $_SESSION['orders'][$_GET['currentOrder']],		
			));	
			return $result;		
		}else{
			$getLanguges=$langugeTable->allLanguges();
			$getCategories=$categoryTable->getallCategories();
			$districtLists = $districtTable->allDistricts();
			$get_all_radius = $radiusTable->getallRadius();
			$get_all_periods= $packagesperoidTable->allperiodofpackages();
			$get_all_dimensions= $imagedimensionsTable->getallDimensions()->buffer();
			$get_adMode= $adstypeTable->alladstypes()->buffer();
			$base_range = $numwordsTable->baseRange();
			$result = new ViewModel(array(
				'all_languages'           =>$getLanguges,
				'all_categories'          =>$getCategories,
				'list_districts'          => $districtLists,
				'list_radius'             => $get_all_radius,
				'list_periodfor_pakages'   => $get_all_periods,
				'list_image_dimensions'   => $get_all_dimensions,
				'list_admodes'         => $get_adMode,
				'base_range'         => $base_range,
			));	
			return $result;	
		}
	}
	function frechenseeAdPostingAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$langugeTable=$this->getServiceLocator()->get('Category\Model\LanguageFactory');
		$categoryTable=$this->getServiceLocator()->get('Category\Model\CategoryFactory');
		$districtTable=$this->getServiceLocator()->get('Category\Model\DistrictsFactory');	
		$areaTable=$this->getServiceLocator()->get('Category\Model\AreaFactory');
		$locationTable=$this->getServiceLocator()->get('Category\Model\LocationFactory');
		$radiusTable=$this->getServiceLocator()->get('Category\Model\RadiusFactory');
		$packagesperoidTable=$this->getServiceLocator()->get('Category\Model\PeriodOfPackagesFactory');
		$imagedimensionsTable=$this->getServiceLocator()->get('Category\Model\ImageDimensionsFactory');
		$adstypeTable=$this->getServiceLocator()->get('Category\Model\AddTypeFactory');
		$numwordsTable=$this->getServiceLocator()->get('Category\Model\NumberWordsFactory');
		if(isset($_POST['ses_current_order']) && $_POST['ses_current_order']!=''){
			$update_session_order=$_POST['ses_current_order'];
			$main_array=array();
			$paper_print=array();
			$magazine=array();
			$home_delivery=array();
			foreach($_POST as $key=>$value){
				if(strpos($key,'paper') !== false) {
					if( $_POST['paper_populationpaperdrop'] != ''&& $value!='' )
					{
						$paper_print[$key]=$value;
					}
				}else if(strpos($key,'magazine') !== false){
					if( $_POST['magazine_titleMagazine'] != '' && $value!='')
					{
						$magazine[$key]=$value;
					}
				}else if(strpos($key,'home') !== false){
				if( $_POST['home_titleHome'] != '' && $value!='' )
					{
						$home_delivery[$key]=$value;
					}
				}else{
					$main_array[$key]=$value;
				}
				$_SESSION['orders'][$update_session_order]['Main_array']=$main_array;				
				if(!empty($paper_print)){
					$_SESSION['orders'][$update_session_order]['Print_Paper']=$paper_print;
				}
				if(count($magazine)>0){
					$_SESSION['orders'][$update_session_order]['Magazine']=$magazine;
				}
				if(!empty($home_delivery)){
					$_SESSION['orders'][$update_session_order]['Home_delivery']=$home_delivery;
				} 	
				if( !isset($_POST['paper_print']) ) {
					unset($_SESSION['orders'][$update_session_order]['Print_Paper']);
				}
				if( !isset($_POST['magazine_magazineCheck']) ){
					unset($_SESSION['orders'][$update_session_order]['Magazine']);
				}
				if( !isset($_POST['home_homedelevarycheck']) ){
					unset($_SESSION['orders'][$update_session_order]['Home_delivery']);
				}
			}
			return $this->redirect()->toUrl($baseUrl.'users/confirm-order');		
		}else if(isset($_POST['language'])){
		    $main_array=array();
			$paper_print=array();
			$magazine=array();
			$home_delivery=array();
			foreach($_POST as $key=>$value){
				if(strpos($key,'paper') !== false) {
					if( $_POST['paper_populationpaperdrop'] != '' && $value!='')
					{
						$paper_print[$key]=$value;
					}
				}else if(strpos($key,'magazine') !== false){
					if( $_POST['magazine_titleMagazine'] != '' && $value!='')
					{
						$magazine[$key]=$value;
					}
				}else if(strpos($key,'home') !== false){
					if( $_POST['home_titleHome'] != '' && $value!='')
					{
						$home_delivery[$key]=$value;
					}
				}else{
					$main_array[$key]=$value;
				}
				
			}		   
			if(isset($_SESSION['orders'])){	
				$orderCount=count($_SESSION['orders']);					
			}else{	
				$orderCount=0;	
				$user_session = new Container('orders');
				$_SESSION['orders']=array();
			}				
				$_SESSION['orders'][$orderCount]['Main_array']=$main_array;				
				if(!empty($paper_print)){
					$_SESSION['orders'][$orderCount]['Print_Paper']=$paper_print;
				}
				if(count($magazine)>0){
					$_SESSION['orders'][$orderCount]['Magazine']=$magazine;
				}
				if(!empty($home_delivery)){
					$_SESSION['orders'][$orderCount]['Home_delivery']=$home_delivery;
				} 
			return $this->redirect()->toUrl($baseUrl.'users/confirm-order');		
		}else if(isset($_GET['currentOrder']) && $_GET['currentOrder']!=''){
			$getLanguges=$langugeTable->allLanguges();
			$getCategories=$categoryTable->getallCategories();
			$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
			$userdetails = $usersTable->getuserDetailes($_SESSION['user']['user_id']);
			$dist_details = $districtTable->getallDistrict($userdetails->district_id);
			$area_details = $areaTable->getAreasWithAreaId($userdetails->area_id);
			$getalllocations=$locationTable->getLoations($userdetails->district_id,$userdetails->area_id);
			$get_all_radius = $radiusTable->getallRadius();
			$get_all_periods= $packagesperoidTable->allperiodofpackages();
			$get_all_dimensions= $imagedimensionsTable->getallDimensions()->buffer();
			$get_adMode= $adstypeTable->alladstypes()->buffer();
			$base_range = $numwordsTable->baseRange();
			$result = new ViewModel(array(
				'all_languages'           => $getLanguges,
				'all_categories'          => $getCategories,
				'dist_name'          	  =>$dist_details->district_name,
				'dist_id'          	      =>$dist_details->district_id,
				'area_id'          	      =>$area_details->area_id,
				'area_name'          	  =>$area_details->area_name,
				'getalllocations'         =>$getalllocations,
				'list_radius'             => $get_all_radius,
				'list_periodfor_pakages'  => $get_all_periods,
				'list_image_dimensions'   => $get_all_dimensions,
				'list_admodes'            => $get_adMode,
				'base_range'              => $base_range,
				'session_data'            => $_SESSION['orders'][$_GET['currentOrder']],		
			));	
			return $result;		
		}else{
			$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
			$userdetails = $usersTable->getuserDetailes($_SESSION['user']['user_id']);
			$getLanguges=$langugeTable->allLanguges();
			$getCategories=$categoryTable->getallCategories();			
			$dist_details = $districtTable->getallDistrict($userdetails->district_id);
			$area_details = $areaTable->getAreasWithAreaId($userdetails->area_id);
			$getalllocations=$locationTable->getLoations($userdetails->district_id,$userdetails->area_id);
			$get_all_radius = $radiusTable->getallRadius();
			$get_all_periods= $packagesperoidTable->allperiodofpackages();
			$get_all_dimensions= $imagedimensionsTable->getallDimensions()->buffer();
			$get_adMode= $adstypeTable->alladstypes()->buffer();
			$base_range = $numwordsTable->baseRange();
			$result = new ViewModel(array(
				'userdetails'           =>$userdetails,
				'all_languages'           =>$getLanguges,
				'all_categories'          =>$getCategories,				
				'dist_name'          	  =>$dist_details->district_name,
				'dist_id'          	      =>$dist_details->district_id,
				'area_id'          	      =>$area_details->area_id,
				'area_name'          	  =>$area_details->area_name,
				'getalllocations'         =>$getalllocations,
				'list_radius'             => $get_all_radius,
				'list_periodfor_pakages'   => $get_all_periods,
				'list_image_dimensions'   => $get_all_dimensions,
				'list_admodes'         => $get_adMode,
				'base_range'         => $base_range,
			));	
			return $result;	
		}
	}
	public function checkDimensionsAction(){		
		$image_info = getimagesize($_FILES["file"]["tmp_name"]);
		$image_width = $image_info[0];
		$image_height = $image_info[1];
		$demsion=$image_width.'*'.$image_height;
		$imagedimensionsTable=$this->getServiceLocator()->get('Category\Model\ImageDimensionsFactory');
		$checkDimensions=$imagedimensionsTable->checkDimensions($demsion);
		if($checkDimensions->count()>0){
			$priceDimension=$checkDimensions->current()->dimension_amount;
			$result = new JsonModel(array(	
				'success'         =>'success',
				'price_dimension' =>$priceDimension,
			));	
		}else{
			$result = new JsonModel(array(
				'success'         =>'not success',
				'price_dimension' =>'',
			));	
		}
		return $result;
	}
	public function priceDaysAction(){
		$dayamountsTable=$this->getServiceLocator()->get('Category\Model\DayAmountsFactory');
		$getamounts_week_ends=$dayamountsTable->getallDayAmounts();
		$weekdays=$_POST['weekday'];
		$weekends=$_POST['weekend'];
		$w_days='';
		$w_ends='';
		if($getamounts_week_ends->count()>0){
			foreach($getamounts_week_ends as $wd_we){
				if($wd_we->day_type=='Week days'){
					$w_days=$wd_we->day_type_amount * $weekdays;
				}else if($wd_we->day_type=='Weekend days'){
					$w_ends=$wd_we->day_type_amount * $weekends;
				}
			}
		}else{
			$w_days='';
			$w_ends='';
		}
		$result = new JsonModel(array(
				'success'         =>'success',
				'week_days' =>$w_days,
				'week_ends' =>$w_ends,
			));	
		return $result;
	}
	public function getRadiusPricesAction(){
		$radiusTable=$this->getServiceLocator()->get('Category\Model\RadiusFactory');
		$get_amounts=$radiusTable->getRadiusInfo($_POST['radius_id']);
		$amount=$get_amounts->amount_for_disatnce;
		$result = new JsonModel(array(
				'output' =>'success',
				'amount' =>$amount,
			));	
		return $result;
	}
	public function getPeriodPricesAction(){
		$packagesperoidTable=$this->getServiceLocator()->get('Category\Model\PeriodOfPackagesFactory');
		$get_amounts=$packagesperoidTable->getperiodpackage($_POST['period_pakage_id']);
		$amount=$get_amounts->time_period_amount;
		$result = new JsonModel(array(
				'output' =>'success',
				'amount' =>$amount,
			));	
		return $result;
	}
	public function getPaperPricesAction(){
		$paperTable=$this->getServiceLocator()->get('Category\Model\PaperCriculationFactory');
		$get_amounts=$paperTable->getPaperInfo($_POST['paper_cir_id']);
		$amount=$get_amounts->amount_paper;
		$result = new JsonModel(array(
				'output' =>'success',
				'amount' =>$amount,
			));	
		return $result;
	}
	public function getLetterPricesAction(){
		$numwordsTable=$this->getServiceLocator()->get('Category\Model\NumberWordsFactory');
		$getAllnumbers=$numwordsTable->allNumbersRange();
		$base_range = $numwordsTable->baseRange();
		$len_letters=$_POST['len_letter'];
		$b_low_limit='';
		$b_upper_limit='';
		$base_range_amount='';
		$base_current_range=explode('-',$base_range->num_words);
		$b_low_limit=$base_current_range['0'];
		$b_upper_limit=$base_current_range['1'];
		$base_range_amount=$base_range->words_amount;
		$lowlimit='';
		$upperlimit='';
		$range_price='';
		if(($len_letters>=$b_low_limit) && ($len_letters<=$b_upper_limit)){
					$range_price=$base_range_amount;
		}else{
			if($getAllnumbers->count()>0){
				foreach($getAllnumbers as $lettersRange){
					$currentRange=explode('-',$lettersRange->num_words);
					$lowlimit=$currentRange['0'];
					$upperlimit=$currentRange['1'];
					if(($len_letters>=$lowlimit) && ($len_letters<=$upperlimit)){
						$range_price=($base_range_amount)+($lettersRange->words_amount);
					}
				}
			}
		}
		$result = new JsonModel(array(
				'output' =>'success',
				'amount' =>$range_price,
			));	
		return $result;
	}
	public function confirmOrderAction(){
		$_SESSION['orders']['total_amount']='';
		$_SESSION['orders']['discount_amount']='';
		$_SESSION['orders']['discount_percent']='';
		$sentnotificationTable=$this->getServiceLocator()->get('Users\Model\SentNotificationsFactory');
		$currentDate=date("Y-m-d");
		$get_offers=$sentnotificationTable->getUserOffers($_SESSION['user']['user_id'],$currentDate);
		$result = new ViewModel(array(
				'getUserOffers'=>$get_offers,
			));	
		return $result;
	}
	public function notificationsAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
	    $usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
		$sentnotificationTable=$this->getServiceLocator()->get('Users\Model\SentNotificationsFactory');
		$sent_notification_messages=$sentnotificationTable->getusernotifications($_SESSION['user']['user_id']);
		if($sent_notification_messages){
			$sentnotificationTable=$this->getServiceLocator()->get('Users\Model\SentNotificationsFactory');
		    $count_notification_messages=$sentnotificationTable->getcountusernotifications($_SESSION['user']['user_id']);
		}
		$result = new ViewModel(array(
				'sent_notification_messages'=>$sent_notification_messages,
				'count_notification_messages' =>count($count_notification_messages),
			));	
		return $result;	
	}	
	public function notificationsUpdateAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
	    $usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
		$sentnotificationTable=$this->getServiceLocator()->get('Users\Model\SentNotificationsFactory');
		$count_updatenotification_messages=$sentnotificationTable->updatecountstatus($_SESSION['user']['user_id']);
		$result = new JsonModel(array(
				'output' =>'success',
			));	
		return $result;	
	}
	public function userorderviewAction(){
		$categoryTable=$this->getServiceLocator()->get('Category\Model\CategoryFactory');
		$categoryAll=$categoryTable->getallCategories();
		$result = new ViewModel(array(
			'categoryAll'=>$categoryAll,
		));	
		return $result;	
	}
	public function userorderviewAjaxAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$basePath = $baseUrlArr['basePath'];
	    $usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
		$ordersViewTable=$this->getServiceLocator()->get('Users\Model\OrdersStatusFactory');
		if(isset($_GET['ordertype']) && $_GET['ordertype']!=""){
			$ordertype=$_GET['ordertype'];
			
		}else{
			$ordertype='';
		}
		if(isset($_GET['cid']) && $_GET['cid']!=""){
			$cid=$_GET['cid'];
		}else{
			$cid='';
		}
		if(isset($_GET['scid']) && $_GET['scid']!=""){
			$scid=$_GET['scid'];
		}else{
			$scid='';
		}
		$userorders_view=$ordersViewTable->viewOrderListWithCategory($_SESSION['user']['user_id'],$ordertype,$cid,$scid);
			$data = array();$i=0;
				if(isset($userorders_view) && $userorders_view!=''){
					foreach($userorders_view as $value){
						if($value->payment_status=="Pending"){	
							$color='pending';
						}else if($value->payment_status=="completed"){
							$color='completed';
						}
						if($value->order_status=="pending"){	
							$color1='pending';
						}else if($value->order_status=="completed"){
							$color1='completed';
						}
						$id=$value->ads_order_id;
						$data[$i]['order_id']   =$value->ads_order_id;
						$data[$i]['user_name']  = $value->user_name;
						$data[$i]['phone_number'] =$value->phone_number;
						$data[$i]['amount'] =$value->tot_amount;
						$data[$i]['admode'] =$value->ads_mode;
						$data[$i]['payment_status'] ='<span class="'.$color.'">'.$value->payment_status.'<span>';
						$data[$i]['order_status'] ='<span class="'.$color1.'">'.$value->order_status.'<span>';
						$data[$i]['Action'] ='<a href="#"><img src="'.$basePath.'/images/edit.png"/></a>&nbsp;&nbsp;&nbsp;<a href="#"><img src="'.$basePath.'/images/cancel.png" width="13px;"></a>';
						$i++;
					}
					$data['aaData'] = $data;
					print_r(json_encode($data['aaData']));exit;
				}
		
		
	}
	public function orderViewAction(){
		$categoryTable=$this->getServiceLocator()->get('Category\Model\CategoryFactory');
		$categoryAll=$categoryTable->getallCategories();
		$subcategoryTable=$this->getServiceLocator()->get('Category\Model\SubCategoryFactory');
		$subcategoryAll=$subcategoryTable->getallSubCategories();
		$result = new ViewModel(array(
			'categoryAll'=>$categoryAll,
			'subcategoryAll'=>$subcategoryAll,
		));	
		return $result;	
	}
	public function offlineOrderAction(){
		$categoryTable=$this->getServiceLocator()->get('Category\Model\CategoryFactory');
		$categoryAll=$categoryTable->getallCategories();
		$result = new ViewModel(array(
			'categoryAll'=>$categoryAll,
		));	
		return $result;	
	}
	public function orderViewAjaxAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];	
		$basePath = $baseUrlArr['basePath'];
	    $usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
		$ordersViewTable=$this->getServiceLocator()->get('Users\Model\OrdersStatusFactory');
		$userinfo_orders_view=$usersTable->getuserDetailes($_SESSION['user']['user_id']);
		if($userinfo_orders_view){
			$district_id=$userinfo_orders_view->district_id;
			$area_id=$userinfo_orders_view->area_id;
			$location_id=$userinfo_orders_view->location_id;
			if(isset($_GET['cid']) && $_GET['cid']!=""){
				$cid=$_GET['cid'];
			}else{
				$cid='';
			}
			if(isset($_GET['scid']) && $_GET['scid']!=""){
				$scid=$_GET['scid'];
			}else{
				$scid='';
			}
			$franchiseeorders_view=$ordersViewTable->franchiseeviewOrderList($_SESSION['user']['user_id'],$district_id,$area_id,$location_id,$cid,$scid,$_GET['payment_mode']);
			$data = array();$i=0;
			if(isset($franchiseeorders_view) && $franchiseeorders_view!=''){
				foreach($franchiseeorders_view as $value){	
					if($_SESSION['user']['user_id']==$value->user_id){
						$user_name=$value->guest_email;
						$user_phone=$value->guest_phone_number;
					}else{
						$user_name=$value->user_name;
						$user_phone=$value->phone_number;
					}
					$id=$value->ads_order_id;
					$data[$i]['order_id']   =$value->ads_order_id;
					$data[$i]['user_name']  = $user_name;
					$data[$i]['phone_number'] =$user_phone;
					$data[$i]['amount'] =$value->tot_amount;
					$data[$i]['payment_status'] =$value->payment_status;
					$data[$i]['order_status'] =$value->order_status;
					$i++;
				}
				$data['aaData'] = $data;
				print_r(json_encode($data['aaData']));exit;
			}else{
				echo '1';exit;
			}
		}
	}
	public function orderOfflineViewAjaxAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$basePath = $baseUrlArr['basePath'];		
	    $usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
		$ordersViewTable=$this->getServiceLocator()->get('Users\Model\OrdersStatusFactory');
		$userinfo_orders_view=$usersTable->getuserDetailes($_SESSION['user']['user_id']);
		if($userinfo_orders_view){
			$district_id=$userinfo_orders_view->district_id;
			$area_id=$userinfo_orders_view->area_id;
			$location_id=$userinfo_orders_view->location_id;
			if(isset($_GET['cid']) && $_GET['cid']!=""){
				$cid=$_GET['cid'];
			}else{
				$cid='';
			}
			if(isset($_GET['scid']) && $_GET['scid']!=""){
				$scid=$_GET['scid'];
			}else{
				$scid='';
			}
			$franchiseeorders_view=$ordersViewTable->franchiseeviewOrderList($_SESSION['user']['user_id'],$district_id,$area_id,$location_id,$cid,$scid,$_GET['payment_mode']);
			$data = array();$i=0;
			if(isset($franchiseeorders_view) && $franchiseeorders_view!=''){
				foreach($franchiseeorders_view as $value){
					if($_SESSION['user']['user_id']==$value->user_id){
						$user_name=$value->guest_email;
						$user_phone=$value->guest_phone_number;
					}else{
						$user_name=$value->user_name;
						$user_phone=$value->phone_number;
					}
					if($value->amount_paid==0){
						$amount_paid='paid';
					}else{
						$amount_paid=$value->amount_paid;
					}
					$id=$value->ads_order_id;
					$data[$i]['order_id']   =$value->ads_order_id;
					$data[$i]['user_name']  = $user_name;
					$data[$i]['phone_number'] =$user_phone;
					$data[$i]['amount'] =$value->tot_amount;
					$data[$i]['amount_paid'] =$amount_paid;
					$data[$i]['payment_status'] =$value->payment_status;
					$data[$i]['order_status'] =$value->order_status;
					if($value->amount_paid==0){
						$data[$i]['Action'] ='<a href="#" title="Edit"><img src="'.$basePath.'/images/edit.png"/></a>&nbsp;&nbsp;&nbsp;<a href="#"><img src="'.$basePath.'/images/cancel.png" width="13px;"></a>';
					}else{
						$data[$i]['Action'] ='<a href="edit-order?orderid='.$id.'" title="Edit"><img src="'.$basePath.'/images/edit.png"/></a>&nbsp;&nbsp;&nbsp;<a href="#"><img src="'.$basePath.'/images/cancel.png" width="13px;"></a>';
					}
					$i++;
				}
				$data['aaData'] = $data;
				print_r(json_encode($data['aaData']));exit;
			}else{
				echo '1';exit;
			}
		}
	}
	public function editOrderAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];		
	    $usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
		$ordersdetailsViewTable=$this->getServiceLocator()->get('Users\Model\OrdersStatusFactory');	
		if(isset($_POST['hid_order_id']) && $_POST['hid_order_id']!=""){
			$dueAmount=$_POST['due_amount']-$_POST['paidAmount'];
			$userinfo_orders_view=$usersTable->getuserDetailes($_SESSION['user']['user_id']);
			$orderdeatails_status = $ordersdetailsViewTable->updateFrenchseeStaus($_POST['hid_order_id'],$dueAmount,$_POST['paymentStatus']);
			global $offlineOrderSubject;
			global $offlineOrderMessage;
			$date = date("Y-m-d");
			$body=$offlineOrderMessage;
			$body = str_replace("<FULLNAME>",$_POST['inputUserName'], $body);
			$body = str_replace("<ORDERID>",$_POST['hid_order_id'], $body);
			$body = str_replace("<DATE>",$date, $body);
			$body = str_replace("<USERNAME>",$_POST['inputEmail'], $body);
			$body = str_replace("<ORDERTOTAL>",$_POST['totalAmount'], $body);
			$body = str_replace("<PAYMENTSTATUS>",$_POST['paymentStatus'], $body);
			if($_POST['inputEmail']==$userinfo_orders_view->email){
				$to=$userinfo_orders_view->email;
			}else{
				$to=$_POST['inputEmail'];
			}
			$sentMail=sendMail($to,$offlineOrderSubject,$body);
			if($sentMail>0){
				return $result = new JsonModel(array(					
					'output' => 'success',
				));	
			}else{
				return $result = new JsonModel(array(	
					'output' => 'server-error',
				));	
			}
			$adminDetails=$usersTable->getAdminDeatils();
			if(isset($adminDetails)){
				$bodyAdmin=$offlineOrderMessage;
				$admin='Admin';
				$bodyAdmin = str_replace("<FULLNAME>",$admin, $bodyAdmin);
				$bodyAdmin = str_replace("<ORDERID>",$_POST['hid_order_id'], $bodyAdmin);
				$bodyAdmin = str_replace("<DATE>",$date, $bodyAdmin);
				$bodyAdmin = str_replace("<USERNAME>",$_POST['inputEmail'], $bodyAdmin);
				$bodyAdmin = str_replace("<ORDERTOTAL>",$_POST['totalAmount'], $bodyAdmin);
				$bodyAdmin = str_replace("<PAYMENTSTATUS>",$_POST['paymentStatus'], $bodyAdmin);
				$adminTo=$adminDetails->email;
				$adminSentMail=sendMail($adminTo,$offlineOrderSubject,$bodyAdmin);
				if($adminSentMail>0){
					return $result = new JsonModel(array(					
						'output' => 'success',
					));	
				}else{
					return $result = new JsonModel(array(	
						'output' => 'server-error',
					));	
				}
			}
			return $this->redirect()->toUrl($baseUrl.'users/offline-order');		
		}else if(isset($_GET['orderid']) && $_GET['orderid']!=''){
			$userinfo_orders_view=$usersTable->getuserDetailes($_SESSION['user']['user_id']);
			$orderdeatails=$ordersdetailsViewTable->viewOrdersDetails($_GET['orderid']);
			$result = new ViewModel(array(
				'userinfo_orders_view'=>$userinfo_orders_view,
				'orderdeatails'=>$orderdeatails,
			));	
			return $result;	
		}
	}
	public function expiredAction(){
		
		$usersTable=$this->getServiceLocator()->get('Users\Model\UsersFactory');
		$offersTable=$this->getServiceLocator()->get('Users\Model\OffersFactory');
		$sentnotificationTable=$this->getServiceLocator()->get('Users\Model\SentNotificationsFactory');
		$expired_date_offers=$offersTable->getallofferRecords();
		if($expired_date_offers->count()>0)
		{
			foreach($expired_date_offers as $expiredcontent)
			{
				$todays_date = date("Y-m-d");
				$today = strtotime($todays_date);
				$exp_date=$expiredcontent->ending_date;
				$offerid=$expiredcontent->offer_id;
				$expiration_date = strtotime($exp_date);
				if ($expiration_date < $today)
				{
					$expired_date_offers_status=$offersTable->expireddateStatus($offerid);
				}
			}
			
		}
		echo "Expired dates status changed";exit;
	}
	public function unsetSessionDivAction(){
		if(isset($_POST['session_div']) && $_POST['session_div']!=''){
			$incrValue=$_POST['incr_value'];
			if($_POST['session_div']=='paper'){
				unset($_SESSION['orders'][$incrValue]['Print_Paper']);
			}elseif($_POST['session_div']=='magazine'){
				unset($_SESSION['orders'][$incrValue]['Magazine']);
			}elseif($_POST['session_div']=='home'){
				unset($_SESSION['orders'][$incrValue]['Home_delivery']);
			}
			if(!isset($_SESSION['orders'][$incrValue]['Print_Paper']) && !isset($_SESSION['orders'][$incrValue]['Magazine'])
			&& !isset($_SESSION['orders'][$incrValue]['Home_delivery'])){
				unset($_SESSION['orders'][$incrValue]);
			}
			$result = new JsonModel(array(
				'output' =>'success',
			));	
			return $result;
		}
	}
	public function getDiscountTotalAction(){
		if(isset($_POST['garndTotal']) && $_POST['garndTotal']!=''){
			$ordermainTable=$this->getServiceLocator()->get('Users\Model\OrdersStatusFactory');
			$offersTable=$this->getServiceLocator()->get('Users\Model\OffersFactory');
			$overallOrdertotal=$ordermainTable->getOverAllOrderstotal($_SESSION['user']['user_id']);
			$sumoforderstotal='';
			foreach($overallOrdertotal as $overallorder){
				$sumoforderstotal+=$overallorder->tot_amount;
			}
			if($sumoforderstotal!=''){
				$totalAmount=$_POST['garndTotal']+$sumoforderstotal;
			}else{
				$totalAmount=$_POST['garndTotal'];
			}
			$getOfferDetails=$offersTable->editoffer($_POST['offerId']);
			if($totalAmount>=$getOfferDetails->offer_amount){
				$discount_pecentage=$getOfferDetails->percent_discount;
				$calDiscount=$_POST['garndTotal']*($discount_pecentage/100);
				$remainingAmount=$_POST['garndTotal']-$calDiscount;
				$_SESSION['orders']['total_amount']=$remainingAmount;
				$_SESSION['orders']['discount_amount']=$getOfferDetails->offer_amount;
				$_SESSION['orders']['discount_percent']=$getOfferDetails->percent_discount;
				$result = new JsonModel(array(
					'output' =>'success',
					'calDiscount' =>$remainingAmount,
				));
			}else{
				$remainingAmount=$_POST['garndTotal'];
				$_SESSION['orders']['total_amount']=$remainingAmount;
				$_SESSION['orders']['discount_amount']='';
				$_SESSION['orders']['discount_percent']='';
				$result = new JsonModel(array(
					'output' =>'not success',
					'calDiscount' =>$remainingAmount,
				));
			}				
			return $result;	
		}		
	}
	public function sessionUpdateAdmodeAction(){
		if(isset($_POST['adMode']) && $_POST['adMode']!=''){ 
			$_SESSION['orders']['ad_mode']=$_POST['adMode'];
			if(isset($_SESSION['orders']['total_amount']) && $_SESSION['orders']['total_amount']==''){ 
				$_SESSION['orders']['total_amount']=$_POST['grandTotal'];
			}else{ 
				$_SESSION['orders']['total_amount']=$_SESSION['orders']['total_amount'];
			}
			if(isset($_SESSION['orders']['discount_amount']) && $_SESSION['orders']['discount_amount']==''){
				$_SESSION['orders']['discount_amount']='';
			}else{
				$_SESSION['orders']['discount_amount']=$_SESSION['orders']['discount_amount'];
			}
			if(isset($_SESSION['orders']['discount_percent']) && $_SESSION['orders']['discount_percent']==''){
				$_SESSION['orders']['discount_percent']='';
			}else{
				$_SESSION['orders']['discount_percent']=$_SESSION['orders']['discount_percent'];
			}
			echo 'sucess';exit;
		}
	}
	public function orderSaveAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$ordermainTable=$this->getServiceLocator()->get('Users\Model\OrderMainsFactory');
		$orderinfoTable=$this->getServiceLocator()->get('Users\Model\OrdersInfoFactory');
		$orderstatusTable=$this->getServiceLocator()->get('Users\Model\OrdersStatusFactory');
		$addOrderId=$orderstatusTable->addOrderstatus();
		if($addOrderId>0){
			for($i=0;$i<count($_SESSION['orders']);$i++){
				if(!isset($_SESSION['orders'][$i])){ continue; }
				$addOrderMain_id=$ordermainTable->addOrder($addOrderId,$_SESSION['orders'][$i]['Main_array']);
				if($addOrderMain_id>0){ 
					$main_id=$addOrderMain_id;
					if(isset($_SESSION['orders'][$i]['Print_Paper'])
					&& !isset($_SESSION['orders'][$i]['Magazine'])
					&& !isset($_SESSION['orders'][$i]['Home_delivery'])
					){ 
						$_SESSION['orders'][$i]['Print_Paper']=$_SESSION['orders'][$i]['Print_Paper'];
						$_SESSION['orders'][$i]['Magazine']='';
						$_SESSION['orders'][$i]['Home_delivery']='';						
					}else if(isset($_SESSION['orders'][$i]['Print_Paper'])
					&& isset($_SESSION['orders'][$i]['Magazine']) 
					&& !isset($_SESSION['orders'][$i]['Home_delivery']) )
					{ 
						$_SESSION['orders'][$i]['Print_Paper']=$_SESSION['orders'][$i]['Print_Paper'];
						$_SESSION['orders'][$i]['Magazine']=$_SESSION['orders'][$i]['Magazine'];
						$_SESSION['orders'][$i]['Home_delivery']='';
					}else if(!isset($_SESSION['orders'][$i]['Print_Paper']) 
					&& isset($_SESSION['orders'][$i]['Magazine']) 
					&& !isset($_SESSION['orders'][$i]['Home_delivery']))
					{ 
						$_SESSION['orders'][$i]['Print_Paper']='';
						$_SESSION['orders'][$i]['Magazine']=$_SESSION['orders'][$i]['Magazine'];
						$_SESSION['orders'][$i]['Home_delivery']='';
					}else if(!isset($_SESSION['orders'][$i]['Print_Paper'])
					&& isset($_SESSION['orders'][$i]['Magazine'])
					&& isset($_SESSION['orders'][$i]['Home_delivery']))
					{ 
						$_SESSION['orders'][$i]['Print_Paper']='';
						$_SESSION['orders'][$i]['Magazine']=$_SESSION['orders'][$i]['Magazine'];
						$_SESSION['orders'][$i]['Home_delivery']=$_SESSION['orders'][$i]['Home_delivery'];
					}else if(!isset($_SESSION['orders'][$i]['Print_Paper'])
					&& !isset($_SESSION['orders'][$i]['Magazine'])
					&& isset($_SESSION['orders'][$i]['Home_delivery']))
					{
						$_SESSION['orders'][$i]['Print_Paper']='';
						$_SESSION['orders'][$i]['Magazine']='';
						$_SESSION['orders'][$i]['Home_delivery']=$_SESSION['orders'][$i]['Home_delivery'];
					}elseif(isset($_SESSION['orders'][$i]['Print_Paper'])
					&& !isset($_SESSION['orders'][$i]['Magazine'])
					&& isset($_SESSION['orders'][$i]['Home_delivery']))
					{
						$_SESSION['orders'][$i]['Print_Paper']=$_SESSION['orders'][$i]['Print_Paper'];
						$_SESSION['orders'][$i]['Magazine']='';
						$_SESSION['orders'][$i]['Home_delivery']=$_SESSION['orders'][$i]['Home_delivery'];
					}else if(isset($_SESSION['orders'][$i]['Print_Paper'])
					&& isset($_SESSION['orders'][$i]['Magazine']) 
					&& isset($_SESSION['orders'][$i]['Home_delivery']) )
					{ 
						$_SESSION['orders'][$i]['Print_Paper']=$_SESSION['orders'][$i]['Print_Paper'];
						$_SESSION['orders'][$i]['Magazine']=$_SESSION['orders'][$i]['Magazine'];
						$_SESSION['orders'][$i]['Home_delivery']=$_SESSION['orders'][$i]['Home_delivery'];
					}
					$addOrderMain=$orderinfoTable->addOrderinfo($main_id,$_SESSION['orders'][$i]['Print_Paper'],$_SESSION['orders'][$i]['Magazine'],$_SESSION['orders'][$i]['Home_delivery']);
					if($addOrderMain>0){					
						if($_SESSION['orders']['ad_mode']=='offline'){
						  return $this->redirect()->toUrl($baseUrl.'users/payment-success?oId='.$addOrderId);
						}else if($_SESSION['orders']['ad_mode']=='online'){
						  return $this->redirect()->toUrl($baseUrl.'users/payments?order_id='.$addOrderId);
						}						 
					}				
				}
			}
		}
	}
	public function paymentSuccessAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$paypalUrl = $baseUrlArr['paypalUrl'];
		$token=$this->mt_rand_str('16');
		global $confirmOrderSubject;
	    global $confirmOrderMessage;
		$orderstatusTable=$this->getServiceLocator()->get('Users\Model\OrdersStatusFactory');
		if(isset($_GET['tx']) && $_GET['tx']!=''){			
			$getoderDetail=$orderstatusTable->getOrderInfo_d($_GET['item_number']);
			if(count($getoderDetail)>='0'){
				if($_SESSION['user']['user_type_id']!='2'){
					$userName=$getoderDetail->user_name;
					$to=$getoderDetail->email;
				}else{
					$userName=$getoderDetail->guest_email;
					$to=$getoderDetail->guest_email;
				}
				$orderId=$getoderDetail->ads_order_id;
				$orderAmount=$getoderDetail->tot_amount;
				$orderFrom=$getoderDetail->ads_mode;
				$paymentStatus=$getoderDetail->payment_status;				
				$body=$confirmOrderMessage;
				$body = str_replace("<FULLNAME>",$userName, $body);
				$body = str_replace("<ORDERID>",$orderId, $body);
				$body = str_replace("<ORDERFROM>",$orderFrom, $body);
				$body = str_replace("<USERNAME>",$userName, $body);
				$body = str_replace("<ORDERTOTAL>",$orderAmount, $body);
				$body = str_replace("<PAYMENTSTATUS>",$paymentStatus, $body);
			}
			$sentMail=sendMail($to,$confirmOrderSubject,$body);	
			if($sentMail>0){
				return $this->redirect()->toUrl($baseUrl.'users/order-success');
			}else{
				return $this->redirect()->toUrl($baseUrl.'users/order-success');
			}	
		}else if(isset($_GET['oId']) && $_GET['oId']!=''){
			$oderId=$_GET['oId'];
			$tax_id=$token;	
			$status='Pending';	
			$updateOrderStatus=$orderstatusTable->orderSuccess($oderId,$tax_id,$status);
			if($updateOrderStatus>=0){
				$getoderDetail=$orderstatusTable->getOrderInfo_d($oderId);
				if(count($getoderDetail)>='0'){
					if($_SESSION['user']['user_type_id']!='2'){
						$userName=$getoderDetail->user_name;
						$to=$getoderDetail->email;
					}else{
						$userName=$getoderDetail->guest_email;
						$to=$getoderDetail->guest_email;
					}
					$orderId=$getoderDetail->ads_order_id;
					$orderAmount=$getoderDetail->tot_amount;
					$orderFrom=$getoderDetail->ads_mode;
					$paymentStatus=$getoderDetail->payment_status;				
					$body=$confirmOrderMessage;
					$body = str_replace("<FULLNAME>",$userName, $body);
					$body = str_replace("<ORDERID>",$orderId, $body);
					$body = str_replace("<ORDERFROM>",$orderFrom, $body);
					$body = str_replace("<USERNAME>",$userName, $body);
					$body = str_replace("<ORDERTOTAL>",$orderAmount, $body);
					$body = str_replace("<PAYMENTSTATUS>",$paymentStatus, $body);
				}
				$sentMail=sendMail($to,$confirmOrderSubject,$body);	
				if($sentMail>0){
					return $this->redirect()->toUrl($baseUrl.'users/order-success');
				}else{
					return $this->redirect()->toUrl($baseUrl.'users/order-success');
				}	
			}
		}else{
			return $this->redirect()->toUrl($baseUrl.'users/order-success');
		}		
	}
	public function orderSuccessAction(){
		unset($_SESSION['orders']);		
	}
	public function paymentsAction(){
		
	}
	public function ipnListenerAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$paypalUrl = $baseUrlArr['paypalUrl'];
		$orderstatusTable=$this->getServiceLocator()->get('Users\Model\OrdersStatusFactory');
		// STEP 1: read POST data

		// Reading POSTed data directly from $_POST causes serialization issues with array data in the POST.
		// Instead, read raw POST data from the input stream. 
		
		$raw_post_data = file_get_contents('php://input');
		$raw_post_array = explode('&', $raw_post_data);
		$myPost = array();
		foreach ($raw_post_array as $keyval) {
			$keyval = explode ('=', $keyval);
			if (count($keyval) == 2)
				$myPost[$keyval[0]] = urldecode($keyval[1]);
		}
		// read the IPN message sent from PayPal and prepend 'cmd=_notify-validate'
		$req = 'cmd=_notify-validate';
		if(function_exists('get_magic_quotes_gpc')) {
			$get_magic_quotes_exists = true;
		} 
		foreach ($myPost as $key => $value) {        
			if($get_magic_quotes_exists == true && get_magic_quotes_gpc() == 1) { 
				$value = urlencode(stripslashes($value)); 
			} else {
				$value = urlencode($value);
			}
			$req .= "&$key=$value";
		}

		// Step 2: POST IPN data back to PayPal to validate

		$ch = curl_init($paypalUrl);
		curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $req);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
		curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: Close'));

		// In wamp-like environments that do not come bundled with root authority certificates,
		// please download 'cacert.pem' from "http://curl.haxx.se/docs/caextract.html" and set 
		// the directory path of the certificate as shown below:
		// curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
		if( !($res = curl_exec($ch)) ) {
		// error_log("Got " . curl_error($ch) . " when processing IPN data");
		curl_close($ch);
		exit;
		}
		curl_close($ch);
		
		if (strcmp ($res, "VERIFIED") == 0) {
			// The IPN is verified, process it:
			// check whether the payment_status is Completed
			// check that txn_id has not been previously processed
			// check that receiver_email is your Primary PayPal email
			// check that payment_amount/payment_currency are correct
			// process the notification

			// assign posted variables to local variables
			$item_name = $_POST['item_name'];
			$item_number = $_POST['item_number'];
			$payment_status = $_POST['payment_status'];
			$payment_amount = $_POST['mc_gross'];
			$payment_currency = $_POST['mc_currency'];
			$txn_id = $_POST['txn_id'];
			$receiver_email = $_POST['receiver_email'];
			$payer_email = $_POST['payer_email'];

			// IPN message values depend upon the type of notification sent.
			// To loop through the &_POST array and print the NV pairs to the screen:
			foreach($_POST as $key => $value) {
				echo $key." = ". $value."<br>";
			}			
			$oderId=$item_number;
			$tax_id=$txn_id;
			$status=$payment_status;
			$existsTxtid=$orderstatusTable->checkTxtid($tax_id);
			if($existsTxtid=='0'){
				$updateOrderStatus=$orderstatusTable->orderSuccess($oderId,$tax_id,$status);
				if($updateOrderStatus>=0){
					echo "Transition is successfully";	
				}
			}
		} else if (strcmp ($res, "INVALID") == 0) {
		// IPN invalid, log for manual investigation
			echo "The response from IPN was: <b>" .$res ."</b>";
		}
	}
	public function mt_rand_str ($l, $c = '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ') {
		for ($s = '', $cl = strlen($c)-1, $i = 0; $i < $l; $s .= $c[mt_rand(0, $cl)], ++$i);
		return $s;
	}
	public function subscriberAction(){
			$subscribeTable=$this->getServiceLocator()->get('Users\Model\SubscribeFactory');
			$subscribe=$subscribeTable->addSubscriber($_POST['email']);
			if($subscribe!=0){
				global $subscribemailsubject;
				global $subscribemailMessage;
				$date = date("Y-m-d");
				$body=$subscribemailMessage;
				$body = str_replace("<FULLNAME>",$_POST['email'], $body);
				$to=$_POST['email'];
				$sentMail=sendMail($to,$subscribemailsubject,$body);
				$result = new JsonModel(array(
						'output' =>'success',
						'value' =>1,
				));
				return $result;	
			}
	}
	public function checkSubscriberAction(){
		if(isset($_POST['email'])){
			$subscribeTable=$this->getServiceLocator()->get('Users\Model\SubscribeFactory');
			$subscribeCheck=$subscribeTable->checkEmail($_POST['email']);
			if($subscribeCheck>0){
					$result = new JsonModel(array(					
						'output' 	=> 'success',
						'value' =>'1',
					));					
			}else{
					$result = new JsonModel(array(					
						'output' 	=> 'notsuccess',
					));	
			}
			return $result;		
		}
	}
	public function cronsendnewsletterAction(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
			$subscribeTable=$this->getServiceLocator()->get('Users\Model\SubscribeFactory');
			$emailToSubscriber=$subscribeTable->allSubScribers();
			if($emailToSubscriber->count()>0)
			{ 			
				foreach($emailToSubscriber as $mailcontent)
				{	
					//echo "<pre>";print_r($mailcontent);exit;
					global $newslettermailsubject;				
					global $newslettermailMessage;
					$newsletterTable=$this->getServiceLocator()->get('Users\Model\NewsletterFactory');
					$newsletterAdd=$newsletterTable->allNewsletters();
					//echo "<pre>";print_r($newsletterAdd);exit;
					foreach($newsletterAdd as $newsletter){
					
						$to=$mailcontent->user_email;
						$Email= $mailcontent->user_email;
						$subject=$_POST['subject'];
						$mesage=$_POST['message'];
						$body=$newslettermailMessage;
						$unsubscribelink="<a target='_blank' href='http://" . $_SERVER['HTTP_HOST']."/unsubscribe/".base64_encode($mailcontent->user_email)."'>Unsubscribe</a>";
						$body = str_replace("<FULLNAME>",$Email, $body);
						$body = str_replace("<MESSAGE>",$mesage, $body);
						$body = str_replace("<UNSUBSCRIBED>",$unsubscribelink, $body);
						echo $body;exit;
						//$sentmailall=sendMail($to,$subject,$body);
						/*if($sentmailall){
							return new JsonModel(array(
								'status'	=> 'Mail Sent Successfully',
								'value'		=> 1,
							));
						}else{
							return new JsonModel(array(
								'status'	=> 'Mail Not Sent Successfully',
								'value'		=> 0,
							));
						}*/
					}
				}
				return new JsonModel(array(
						'output'	=> 'success',
						'value'		=> 1,
				));	
			}else {
				return new JsonModel(array(
						'output'	=> 'Not Success',
						'value'		=> 0,
				));
			}
	}
	public function unsubscribe(){
		$baseUrls = $this->getServiceLocator()->get('config');
		$baseUrlArr = $baseUrls['urls'];
		$baseUrl = $baseUrlArr['baseUrl'];
		$subscribeTable=$this->getServiceLocator()->get('Users\Model\SubscribeFactory');
		$emailToSubscriber=$subscribeTable->updateSubScriberMailStatus($_GET);
	
	}
}
	

